<?php

namespace App\Modules\LuckDraw\UserTag;

use App\Http\Model\User;
use App\Modules\LuckDraw\Models\DrawLogModel;
use phpDocumentor\Reflection\DocBlock\Tags\Formatter;

class ConsumptionRegisterUserTag implements UserTagInterface {
    private $_luckId;
    private $_userId;
    private $_strategyPool;
    public function __construct(int $luckId, int $_userId, object $strategyPool) {
        $this->_luckId = $luckId;
        $this->_userId = $_userId;
        $this->_strategyPool = $strategyPool;
    }

    public function getStrategyPool():?array{
        if (empty($this->_strategyPool)) {
            return [];
        }
        //判断是不是走个人奖池
        if ($this->_isPersonal()) {
            return [$this->_strategyPool->personal->strategy, $this->_strategyPool->personal->pool];
        }
        //获取用户消费信息
        $total = $this->_getConsumptionTotalWeek();

        // 判断 新用户注册奖池
        if ($this->_isRegister()) {
            $userRegisterTime = $this -> getUserRegisterTime();
            // write_log('ConsumptionRegisterUserTag','新用户注册奖池-'.$this->_userId,[$userRegisterTime,$this->_strategyPool->register]);
            if ($userRegisterTime>0){
                $register_duration_day = $this->_strategyPool->register->register_duration_day ?? 0;
                # 注册时间7天内 & $total在区间内
                if (
                    ($userRegisterTime + $register_duration_day * 86400 >time())
                    && $total >= $this->_strategyPool->register->consumption_from
                    && $total < $this->_strategyPool->register->consumption_to)
                {
                    return [$this->_strategyPool->register->strategy, $this->_strategyPool->register->pool];
                }
            }
        }

        // 公共奖池
        foreach ($this->_strategyPool->common as $strategyPool) {
            if ($total >= $strategyPool->consumption_from && $total < $strategyPool->consumption_to) {
                return [$strategyPool->strategy, $strategyPool->pool];
            }
        }
        return [];
    }

    private function _isPersonal(){
        return in_array($this->_userId, $this->_strategyPool->personal->user_list);
    }

    // 是否配置新用户奖池
    private function _isRegister(){
        return $this->_strategyPool->register ?? false;
    }

    /**
     * 获取用户的注册时间
     * @return int|mixed
     */
    function getUserRegisterTime(){
        $userInfo = (new User())->get_user($this->_userId, true);
        return $userInfo['create_timestamp'] ?? 0;
    }

    //获取24小时内消费总额
    private function _getConsumptionTotalWeek(){
        return DrawLogModel::query()
            ->where("user_id", $this->_userId)
            ->where("luck_id", $this->_luckId)
            ->where("created_at", ">", date('Y-m-d', strtotime('this week')))
            ->sum("draw_num");
    }
    public function getStrategyAllPool():?array
    {
        if (empty($this->_strategyPool)) {
            return [];
        }
        $data = [];
        //判断是否有个人奖池
        if (isset($this->_strategyPool->personal)) {
            $data[] = [$this->_strategyPool->personal->strategy, $this->_strategyPool->personal->pool, $this->_strategyPool->personal->user_list,'personal'];
        }

        // 判断 新用户注册奖池
        if ($this->_isRegister()) {
            $data[] = [$this->_strategyPool->register->strategy, $this->_strategyPool->register->pool, [],'register'];
        }

        //获取用户消费信息
        if (isset($this->_strategyPool->common)) {
            foreach ($this->_strategyPool->common as $key => $strategyPool) {
                $data[] = [$strategyPool->strategy, $strategyPool->pool,[],'common'.'|'.$key];
            }
        }

        return $data;
    }

    public function getUpdatedUserTagByPoolData(array $newPool): ?array {
        $oldStrategyPool = $this->_strategyPool;
        //获取更改过的奖品信息
        $changedAwards = [];
        foreach ($newPool as $a){
            if (isset($a['old_data'])) {
                $keyOld = sprintf("%s-%s-%s",  $a['old_data']['type'], $a['old_data']['id'], $a['old_data']['time']);
                $keyNew = sprintf("%s-%s-%s",  $a['type'], $a['id'], $a['time']);
                if ($keyOld != $keyNew) {
                    $changedAwards[$keyOld] = $a;
                }
            }
        }

        $needUpdate = false;

        //主要是查看补偿的奖品有没有被改，有被修改的话就更新，没有就算了
        //普通
        if(isset($oldStrategyPool->common)){
            foreach ($oldStrategyPool->common as $pool) {
                if (isset($pool->strategy->ext->awards)) {
                    //对比当前id
                    foreach ($pool->strategy->ext->awards as $award) {
                        $key = sprintf("%s-%s-%s",  $award->type, $award->id, $award->time);
                        if (isset($changedAwards[$key])) {
                            $award->id = $changedAwards[$key]['id'];
                            $award->type = $changedAwards[$key]['type'];
                            $award->time = $changedAwards[$key]['time'];
                            $award->price = $changedAwards[$key]['price'];
                            $needUpdate = true;
                        }
                    }
                }
            }
        }

        //个人
        if(isset($oldStrategyPool->personal)){
            if (isset($oldStrategyPool->personal->strategy->ext->awards) ) {
                //对比当前id
                foreach ($oldStrategyPool->personal->strategy->ext->awards as $award) {
                    $key = sprintf("%s-%s-%s",  $award->type, $award->id, $award->time);
                    if (isset($changedAwards[$key])) {
                        $award->id = $changedAwards[$key]['id'];
                        $award->type = $changedAwards[$key]['type'];
                        $award->time = $changedAwards[$key]['time'];
                        $award->price = $changedAwards[$key]['price'];
                        $needUpdate = true;
                    }
                }
            }
        }

        //注册
        if(isset($oldStrategyPool->registers->trategy->ext->awards)){
            //对比当前id
            foreach ($oldStrategyPool->registers->trategy->ext->awards as $award) {
                $key = sprintf("%s-%s-%s",  $award->type, $award->id, $award->time);
                if (isset($changedAwards[$key])) {
                    $award->id = $changedAwards[$key]['id'];
                    $award->type = $changedAwards[$key]['type'];
                    $award->time = $changedAwards[$key]['time'];
                    $award->price = $changedAwards[$key]['price'];
                    $needUpdate = true;
                }
            }
        }

        //返回修改后的数据
        return [$needUpdate, json_encode($oldStrategyPool)] ;
    }

    //获取所有策略的名字
    public function getAllStrategyAndUserIds(){
        //获取更改过的奖品信息
        $allStrategy = [];
        $userList = [];
        //普通
        if(isset($this->_strategyPool->common)){
            foreach ($this->_strategyPool->common as $pool) {
                if (isset($pool->strategy->name)) {
                    $allStrategy[$pool->strategy->name] = 1;
                }
            }
        }

        //个人 这个标签不循环
        if(isset($this->_strategyPool->personal)){
            if (isset($this->_strategyPool->personal->strategy->name)) {
                $allStrategy[$this->_strategyPool->personal->strategy->name] = 1;
            }
            if (isset($this->_strategyPool->personal->user_list)) {
                $userList = array_merge($userList, $this->_strategyPool->personal->user_list);
            }
        }
        //注册 这个标签不循环
        if(isset($this->_strategyPool->register)){
            if (isset($this->_strategyPool->register->strategy->name)) {
                $allStrategy[$this->_strategyPool->register->strategy->name] = 1;
            }
        }

        return [array_keys($allStrategy), $userList];
    }
}
